<?php
/**
 * 判断PHP版本
 * @staticvar type $_is_php
 * @param type $version
 * @return type 
 */
function is_php($version = '5.0.0')
{
        static $_is_php;
        $version = (string)$version;

        if ( ! isset($_is_php[$version]))
        {
                $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
        }

        return $_is_php[$version];
}

/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_addslashes($string){
	if(!is_array($string)) return addslashes($string);
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

if ( ! function_exists('redirect'))
{
	function redirect($uri = '', $method = 'location', $http_response_code = 302)
	{
		if (!is_array($uri) && preg_match('#^https?://#i', $uri))
		{
			show_404('The url is error');
		}
		$uri = site_url($uri);

		switch($method)
		{
			case 'refresh'	: header("Refresh:0;url=".$uri);
				break;
			default			: header("Location: ".$uri, TRUE, $http_response_code);
				break;
		}
		exit;
	}
}

if(! function_exists('site_url'))
{
	function site_url($uri = '')
	{
		$url = '?';
		$params = array();
        $uris = array();
        $router = Base::load_sys_class('router');
		if(is_array($uri))
		{
            $uris['m'] = isset($uri['m']) ? $uri['m'] : $router->get_module();
            $uris['c'] = isset ($uri['c']) ? $uri['c'] : $router->get_controller();
            $uris['a'] = isset($uri['a']) ? $uri['a'] : $router->get_action();
            foreach($uri as $k => $o)
            {
                $uris[$k] = $o;
            }
			foreach ($uris as $key => $v)
			{
				$params[] = $key . '=' . $v;
			}
			$param = implode('&', $params);
			$url .= $param;
		}else {
			$url = $uri;
		}
		$conf = Base::load_config('system');
		$url = base_url().$conf['index_page'].$url;
		return $url;
	}
}

if(! function_exists('base_url'))
{
	function base_url()
	{
		$conf = Base::load_config('system');
		if($conf['base_url'] == '')
		{
			if (isset($_SERVER['HTTP_HOST']))
			{
				$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
				$base_url .= '://'. $_SERVER['HTTP_HOST'];
				$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
			}
			else{
				$base_url = 'http://localhost/';
			}
			
			$conf['base_url'] = $base_url;
		}
		return $conf['base_url'];
	}
}

if(! function_exists('lang'))
{
	function lang($item = NULL,$m = '')
	{
		static $lang = array();
		if(isset($lang[$item]) && !empty($lang[$item]))
		{
			return $lang[$item];
		}
		$lang_dir = Base::load_config('system','language'); 
		$router = Base::load_sys_class('router');
		$m = (is_null($m) || $m == '') ? $router->get_module() : $m;
        $c = $router->get_controller();
		
		$system_lang_path = LIB_PATH.'languages'.DIRECTORY_SEPARATOR.$lang_dir.DIRECTORY_SEPARATOR.'system.lang.php';
		$lang_path = LIB_PATH.'languages'.DIRECTORY_SEPARATOR.$lang_dir.DIRECTORY_SEPARATOR.$m.'.lang.php';
        $controller_lang_path = LIB_PATH.'languages'.DIRECTORY_SEPARATOR.$lang_dir.DIRECTORY_SEPARATOR.$c.'.lang.php';
		
		if(file_exists($system_lang_path))
		{
			include $system_lang_path;
		}
		if(file_exists($lang_path))
		{
			include $lang_path;
		}
        if(file_exists($controller_lang_path))
        {
            include $controller_lang_path;
        }
		
		if(isset($lang[$item]) && !empty($lang[$item]))
		{
			return $lang[$item];
		}
		return FALSE;
	}
	
	function L($item = NULL,$m = '')
	{
		echo lang($item,$m);
	}
}

/**
 * 获取当前页面完整URL地址
 */
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	return $string;
}
/**
 * URL路径解析，pages 函数的辅助函数
 *
 * @param $par 传入需要解析的变量 默认为，page={$page}
 * @param $url URL地址
 * @return URL
 */
function url_par($par, $url = '') {
	if($url == '') $url = get_url();
	$pos = strpos($url, '?');
	if($pos === false) {
		$url .= '?'.$par;
	} else {
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($querystring, $pars);
		$query_array = array();
		foreach($pars as $k=>$v) {
			$query_array[$k] = $v;
		}
		$querystring = http_build_query($query_array).'&'.$par;
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}

/**
 * 返回分页路径
 * 
 * @param $urlrule 分页规则
 * @param $page 当前页
 * @param $array 需要传递的数组，用于增加额外的方法
 * @return 完整的URL路径
 */
function pageurl($urlrule, $page, $array = array()) {
	if(strpos($urlrule, '#')) {
		$urlrules = explode('#', $urlrule);
		$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
	}
	$findme = array('{$page}');
	$replaceme = array($page);
	if (is_array($array)) foreach ($array as $k=>$v) {
		$findme[] = '{$'.$k.'}';
		$replaceme[] = $v;
	}
	$url = str_replace($findme, $replaceme, $urlrule);
	return $url;
}

/**
 * 分页函数
 * 
 * @param $num 信息总数
 * @param $curr_page 当前分页
 * @param $perpage 每页显示数
 * @param $urlrule URL规则
 * @param $array 需要传递的数组，用于增加额外的方法
 * @return 分页
 */
function pages($num, $curr_page, $perpage = 20, $urlrule = '',$class='', $array = array()) {
	if($urlrule == '') $urlrule = url_par('page={$page}');
	$multipage = '';
	if($num > $perpage) {
		$page = 11;
		$offset = 4;
		$pages = ceil($num / $perpage);
		$from = $curr_page - $offset;
		$to = $curr_page + $offset;
		$more = 0;
		if($page >= $pages) {
			$from = 2;
			$to = $pages-1;
		} else {
			if($from <= 1) {
				$to = $page-1;
				$from = 2;
			}  elseif($to >= $pages) { 
				$from = $pages-($page-2);  
				$to = $pages-1;  
			}
			$more = 1;
		} 
		$multipage .= lang('total').'<b>'.$num.'</b>&nbsp;&nbsp;';
		if($curr_page>0) {
			$multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.lang('previous').'</a>';
			if($curr_page==1) {
				$multipage .= ' <span>1</span>';
			} elseif($curr_page>6 && $more) {
				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
			} else {
				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
			}
		}
		for($i = $from; $i <= $to; $i++) { 
			if($i != $curr_page) { 
				$multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>'; 
			} else { 
				$multipage .= ' <span>'.$i.'</span>'; 
			} 
		} 
		if($curr_page<$pages) {
			if($curr_page<$pages-5 && $more) {
				$multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.lang('next').'</a>';
			} else {
				$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.lang('next').'</a>';
			}
		} elseif($curr_page==$pages) {
			$multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.lang('next').'</a>';
		} else {
			$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.lang('next').'</a>';
		}

	}
	return $multipage;
}

/**
 * 判断email格式是否正确
 * @param $email
 */
function is_email($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

